//
//  CCLoginModel.m
//  Party
//
//  Created by coco on 15/4/7.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCLoginModel.h"
#import "AFHTTPRequestOperationManager+RACSupport.h"
#import <ReactiveMantle/RACSignal+Mantle.h>

@interface CCLoginModel()
@property (nonatomic, strong) RACSignal *loginSignal;
@end
@implementation CCLoginModel

- (id) initWithUserid:(NSString *)userid password:(NSString *)password {
  if (self = [super init]) {
    _userid = userid;
    _password = password;
    [self makeType];
  }
  return self;
}

- (void) makeType {
  _type = 0;
}

- (void) loginWithSuccess:(void(^)(CCLoginResultModel*))success error:(void(^)(NSError*)) errorBlock {
  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  [[[[manager  rac_POST:@"" parameters:[self dictionaryValue]] replayLazily] parseResponseForClass:[CCLoginResultModel class]] subscribeNext:^(id x) {
    success(x);
  } error:^(NSError *error) {
    errorBlock(error);
  } completed:^{
  }];
}

- (RACSignal *) login {
  if (_loginSignal == nil) {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"http://localhost:3000/login?name=%@&password=%@",self.userid,self.password];
    _loginSignal = [[[[manager  rac_GET:url parameters:[self dictionaryValue]]
                                replayLazily]
                               map:^id(RACTuple* value) {
                                 return value.first;
                               }]
                              parseResponseForClass:[CCLoginResultModel class]
                              ];
    
  }
  return _loginSignal;
}

- (void) loginComplate {
  _loginSignal = nil;
}

- (void) dealloc {
  NSLog(@"model dealloc");
}

#pragma mark over
+ (NSDictionary *) JSONKeyPathsByPropertyKey {
  return @{
           @"userid":@"userid",
           @"password":@"password",
           @"type":@"type"
          };
}
@end


@implementation CCLoginResultModel

+ (NSDictionary *) JSONKeyPathsByPropertyKey {
  return @{
           @"code":@"code",
           @"errorDescription":@"description",
           @"sessiondid":@"sessionid"
          };
}
@end